package cn.dc406.labc406mgr.controller;

import cn.dc406.labc406mgr.entity.LendTable;
import cn.dc406.labc406mgr.entity.User;
import cn.dc406.labc406mgr.mapper.LendMapper;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpSession;
import java.util.Date;
import java.util.List;

@RestController
public class LendController {

    @Autowired
    LendMapper lendMapper;

    @CrossOrigin
    @RequestMapping("/getLends")
    List<LendTable>getLends(HttpSession httpSession)
    {
        User user=(User) httpSession.getAttribute("user");
        System.out.println("sessionuser="+user);
        String username= user.getUsername();
        List<LendTable> list=lendMapper.selectLendDetailsAllByUsername(username);
        System.out.println(list);
        return list;
    }

    @CrossOrigin
    @RequestMapping("/returnBack")
    int returnBack(int id)
    {
        LendTable lendTable=new LendTable();
        lendTable.setState("3");
        lendTable.setReturntime(new Date());
        lendTable.setId(id);
        return lendMapper.updateLendStateByID(lendTable);

    }

    @CrossOrigin
    @RequestMapping("/cancelBack")
    int cancelBack(int id)
    {
        LendTable lendTable=new LendTable();
        lendTable.setState("2");
        lendTable.setId(id);
        return lendMapper.updateLendStateByID(lendTable);
    }

    @CrossOrigin
    @PostMapping("/updateLendsByIds")
    int updateLendsByIds(@RequestBody JSONObject jsonObject)
    {
        JSONArray ids=jsonObject.getJSONArray("id");
        System.out.println("LendIds="+ids);
        int res=0;
        for (int i=0;i<ids.size();i++) {
            int id=ids.getInt(i);
            LendTable lendTable=new LendTable();
            lendTable.setState("3");
            lendTable.setReturntime(new Date());
            lendTable.setId(id);
            res += lendMapper.updateLendStateByID(lendTable);
        }

        if(res==ids.size())//影响条数达标
        {
            return 1;
        }else{
            return 0;
        }
    }
}
